﻿﻿﻿require.config({
	urlArgs : "version=20170407",
	paths : {
		'jquery' : '/js/packages/jquery-2.14-min',
		'bootstrap' : '/bootstrap/js/bootstrap.min',
		'bootstraptree' : '/bootstrap/bootstrap-treeview/bootstrap-treeview',
	},
	shim : {
		'bootstrap' : {
			deps : [ 'jquery' ],
			exports : 'bootstrap'
		},
		'bootstraptree' : {
			deps : [ 'jquery' ],
			exports : 'bootstrap'
		}
	}

});


require([ 'jquery', 'bootstrap', 'bootstraptree' ], function($) {

	depotid = null;

	$('#create-te').click(function(){
		genFeature();
	});
	
	function genFeature() {
		console.log("start generate feature")
		//在这里给tree_id赋值,tree_id写在value中，通过var tree_id = $('#show-trees').children('option:selected').val();
		var tree_id = $('#show-trees').children('option:selected').val();
		if(tree_id==null){
			alert('请提供技术关键词分类树！')
			return;
		}
		$.ajax({
			type : 'POST',  
			url : '/applications/prepare', 
			data : {
				"tree_id":tree_id
			},
	        contentType: "application/x-www-form-urlencoded",  
	        dataType : 'json',  
	        success : function(res) {
			   // alert("OK")
			    window.location.href="/graph/showtewin.html";
			}
		});
	}

	$('#insertSiblingButton').click(
			function() {
				if ($('#newKeyValue').val() == '') {
					alert('空不行')
					return;
				}
				//get selected node
				var nodeData = $('#spkey-treeview').treeview('getSelected')[0];
				//console.log('selected')
				//console.log(nodeData)
				$.ajax({
					url : '/fk/savesibkw',
					type : 'GET', //GET
					async : false, //或false,是否异步
					data : {
						flowid : depotid,
						keywordValue : $('#newKeyValue').val(),
						parentid : nodeData.item_parent,
					},
					//timeout:5000,    //超时时间
					dataType : 'json', //返回的数据格式：json/xml/html/script/jsonp/text

					success : function(data, textStatus, jqXHR) {
						//console.log(data)
						//successfully insert to database
						var newData = {
							text : $('#newKeyValue').val(),
							href : '#demo',
							nodes : [],
							item_id : data.id,
							item_parent : data.parentId,
						//tags: ['11']
						};
						$('#spkey-treeview').treeview("addSiblingNode",
								[ nodeData.nodeId, newData ]);
					},
					error : function(xhr, textStatus) {
						//console.log(xhr.responseText)
						//console.log(textStatus)
					},
					complete : function() {
						console.log('结束')
					}
				});

				/*
				console.log('active '+activenode)
				if(activenode!='')
					$('#treeview5').treeview("addNode", [activenode, {node: newData}]);
				 */
			});

	//		document.addEventListener("click", function(e){
	//			console.log(e.target)
	//			console.log(e.srcElement)
	//		})

	defaultData = [];
	function formatData(data) {
		defaultData = [];
		var keys = [];
		var stack = [];
		var treeviewData = [];
		//console.log(data.length)
		var rootNode = [];
		var leftNode = [];

		for ( var o in data) {
			//console.log(data[o].keywordValue + "  " + data[o].parentId)
			if (data[o].parentId == 0) {
				var item = {
					text : data[o].keywordValue,
					href : '#item_' + data[o].id,
					tags : '0',
					nodes : [],
					item_id : data[o].id,
					item_parent : 0,
				//levelll:0,
				//order:0,
				}
				rootNode.push(item);
				//data.splice(o,1);
			} else {
				leftNode.push(data[o])
			}
		}
		data = leftNode;

		for ( var root_index in rootNode) {
			stack = [];
			stack.push(rootNode[root_index])
			while (stack.length > 0) {
				//console.log(stack.length)
				var curr = stack[stack.length - 1];
				var order = 0;
				var find_flag = false;
				for ( var o in data) {
					if (data[o].parentId == curr.item_id) {
						var item = {
							text : data[o].keywordValue,
							href : '#item_' + data[o].id,
							tags : '0',
							nodes : [],
							item_id : data[o].id,
							item_parent : data[o].parentId,
						//level:curr.level+1,
						//order:0,
						}
						//console.log(item)
						//curr.nodes.push(item);
						order = order + 1
						stack.push(item);
						data.splice(o, 1);
						//console.log(data.length)
						find_flag = true;
						break;
					}
				}

				if (find_flag)
					continue;

				if (stack.length > 1) {
					stack[stack.length - 2].nodes.push(curr);
					stack.splice(stack.length - 1, 1);
				} else {
					//console.log(stack[stack.length-1])
					defaultData.push(stack[0]);
					stack = []
					//break;
				}

				//console.log(stack[0]);
			}
		}
		//alert('yes')

	}



	function initSelectableTree() {
		$('#spkey-treeview').treeview({
			color : "#428bca",
			expandIcon : 'glyphicon glyphicon-chevron-right',
			collapseIcon : 'glyphicon glyphicon-chevron-down',
			nodeIcon : 'glyphicon glyphicon-bookmark',
			data : defaultData,
			//multiSelect: $('#chk-select-multi').is(':checked'),
			/*
			onNodeSelected: function(event, node) {
			console.log(node.nodeId+' '+node.text + ' was selected');
			//newData.
			activenode = node.nodeId;
			var nodeData = $('#treeview5').treeview('getSelected')[0];
			//console.log(event.srcElement)
			//console.log(event.target)
			$('#currKeyValue').val(nodeData.text);
			},
			 */
			onNodeUnselected : function(event, node) {
				//console.log(node.text + ' was unselected');
			},
			onNodeAdd : function(nodeId) {
				var newNode = null;
				$.ajax({
					url : '/fk/savekw',
					type : 'GET', //GET
					async : false, //或false,是否异步
					data : {
						flowid : depotid,
						keywordValue : '关键词',
						parentid : nodeId
					},
					//timeout:5000,    //超时时间
					dataType : 'json', //返回的数据格式：json/xml/html/script/jsonp/text

					success : function(data, textStatus, jqXHR) {
						//console.log(data)
						//successfully insert to database
						newNode = [ {
							text : data.keywordValue,
							href : '#demo',
							nodes : [],
							item_id : data.id,
							item_parent : data.parentId,
						//tags: ['11']
						} ];
					},
					error : function(xhr, textStatus) {
						//console.log(xhr.responseText)
					},
					complete : function() {
						//console.log('结束')
					}
				});
				return newNode;

			},
			onNodeRemove : function(rmList) {
				//console.log(Array.isArray(rmList))
				//console.log(rmList)
				var del_status = '';
				$.ajax({
					url : '/fk/removekw',
					type : 'POST', //GET
					async : false, //或false,是否异步
					data : {
						listParam : rmList
					},
					//timeout:5000,    //超时时间
					dataType : 'text', //返回的数据格式：json/xml/html/script/jsonp/text
					success : function(data, textStatus, jqXHR) {
						del_status = 'ok';
					},
					error : function(xhr, textStatus) {
					},
				});
				//console.log(del_status)
				return del_status;
			}
		});
	}
		//Select Depot
		function initKeywordsTreesSet() {
			$.ajax({
				url : '/sptree/all',
				type : 'GET',
				async : false,
				dataType : 'json',
				success : function(data, textStatus, jqXHR) {
					//console.log(data)
					if(data==null||data.length==0){
						$('#no-result-div').css('display','block')
					}else{
						$('#tree-result-div').css('display','block')
						for ( var o in data) {
							//console.log(data[o].name+'  " ":'+data[o].id)
							if (data[o].deleted != 'false') {
								$('#show-trees').append(
										'<option value="' + data[o].id + '">'
												+ data[o].name + '</option>');
								if (depotid == null) {
									depotid = data[o].id;
								}
							}
						}
						if(depotid != null){
							//init sp-tree
							GetAndShowTree(depotid)
						}
					}
				}
			});
		}
		function GetAndShowTree(treeId){
			$.ajax({
				url : '/sptree/readflow',
				type : 'GET', //GET
				async : false, //或false,是否异步
				data : {
					treeId : treeId,
				},
				dataType : 'json', //返回的数据格式：json/xml/html/script/jsonp/text
				success : function(data, textStatus, jqXHR) {
					formatData(data)
					//console.log(data)
					//console.log(textStatus)
					//console.log(jqXHR)
				},
				error : function(xhr, textStatus) {
					console.log(xhr.responseText)
					console.log(textStatus)
				},
				complete : function() {
					//console.log('结束')
				}
			});
			var checkText=$("#show-trees").find("option:selected").text();  //获取Select选择的Text
			var checkValue=$("#show-trees").val(); 
			//console.log(checkText+checkValue)
			initSelectableTree();
		}
		initKeywordsTreesSet();

		$('#show-trees').change(function() {
			console.log($(this).children('option:selected').val());
			console.log($(this).children('option:selected').text());
			
			//console.log(depotid)
			newdepotid = $(this).children('option:selected').val();
			if(depotid == newdepotid){
				//console.log('nothing')
			}
			else{
				depotid = newdepotid
				//console.log('new depot id: '+ depotid)
				GetAndShowTree(depotid)
			}
		});
		
		$("#create-new-tree").click(
				function (){
					if($("#new-tree-name").val().trim()==''){
						alert('请输入关键词分类树名称');
						return;
					}
					
					$.ajax({
						url : '/sptree/newsptree',
						type : 'GET', //GET
						async : false, //或false,是否异步
						data : {
							treeName : $("#new-tree-name").val().trim(),
						},
						dataType : 'json', //返回的数据格式：json/xml/html/script/jsonp/text
						success : function(data, textStatus, jqXHR) {
							$('#show-trees').append(
									'<option value="' + data + '">'
											+ $("#new-tree-name").val().trim() + '</option>');
							$("#show-trees").val(data);
							$("#show-trees").trigger('change')
							
							$('#myModal').modal('hide')
							$("#new-tree-name").val('')
							
							$('#no-result-div').prop('style','display:none')
							$('#tree-result-div').prop('style','display:block')
						}
					});
					//initSelectableTree();
			});
		$("#update-tree").click(function (){
			if($('#update-tree-name').val()==null|| $('#update-tree-name').val()==''){
				alert('请输入关键词分类树名称')
				return;
			}
			
			$.ajax({
				url : '/sptree/renamesptree',
				type : 'GET', //GET
				async : false, //或false,是否异步
				data : {
					treeId :$('#show-trees').children('option:selected').val(),
					treeName :  $('#update-tree-name').val()
				},
				dataType : 'text', //返回的数据格式：json/xml/html/script/jsonp/text
				success : function(data, textStatus, jqXHR) {
					newtext = $('#update-tree-name').val();
					$('#show-trees').children('option:selected').text(newtext)
					$('#updateModal').modal('hide')
				},
			});

		});
		
		$("#delete-tree").click(function (){
			$.ajax({
				url : '/sptree/removesptree',
				type : 'GET', //GET
				async : false, //或false,是否异步
				data : {
					treeId :$('#show-trees').children('option:selected').val(),
					treeName : $('#show-trees').children('option:selected').text()
				},
				dataType : 'text', //返回的数据格式：json/xml/html/script/jsonp/text
				success : function(data, textStatus, jqXHR) {
					$('#show-trees').children('option:selected').remove()
					$("#show-trees").trigger('change')
					$('#deleteModal').modal('hide')
				},
			});

		});
		
		$("#btn-update-modal").click(function (){
			var checkText=$("#show-trees").find("option:selected").text();  //获取Select选择的Text
			//var checkValue=$("#show-trees").val(); 
			//console.log(checkText+checkValue)
			$('#update-tree-name').val(checkText)
			
			$('#updateModal').modal('show')
		});
		
		$("#btn-delete-modal").click(function (){
			var checkText=$("#show-trees").find("option:selected").text();  //获取Select选择的Text
			$('#delete-prompt').text('确定要删除技术关键词库"'+checkText+'"吗?');
			$('#deleteModal').modal('show')
		});

	});